package com.unitd.comm.web;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.unitd.frame.springweb.controller.SuperController;
import com.unitd.frame.sso.common.helper.SSOHelper;
import com.unitd.frame.sso.common.token.SSOToken;
import com.unitd.frame.sso.exception.SsoException;
import com.unitd.modules.sys.service.ISysMenuService;
import com.unitd.modules.sys.service.ISysRoleService;
import com.unitd.modules.sys.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @desc 自定义的SpringMVC的基础控制器类, 一般情况下自定义Controller类都继承自此类
 * @filename BaseController.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2016/10/4
 */
public class BaseController extends SuperController implements HandlerInterceptor {

	@Autowired
	protected ISysUserService sysUserService;
	@Autowired
	private ISysMenuService sysMenuService;
	@Autowired
	private ISysRoleService sysRoleService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
		// 方法调用后调用该方法，返回数据给请求页
		if (isLegalView(modelAndView)) {
			modelAndView.addObject("currentUser", sysUserService.selectByPrimaryKey(getCurrentUserId()));
			modelAndView.addObject("roleNames", sysRoleService.findRoleNameByUserId(getCurrentUserId()));
			modelAndView.addObject("menuList", sysMenuService.findTreeListByUserId(getCurrentUserId()));
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
	}

	/**
	 * @desc 获取当前登录用户的ID, 实际上为用户登录时, 将用户ID设置为SSOToken的ID, 然后再此取出
	 * @return 当前登录用户ID
	 */
	protected String getCurrentUserId() {
		return this.getSSOToken().getId().toString();
	}

	/**
	 * @desc 获取当前http请求中的token对象
	 * @return 请求中的token对象
	 */
	protected SSOToken getSSOToken() {
		SSOToken ssoToken = SSOHelper.attrToken(this.request);
		if (ssoToken == null) {
			throw new SsoException("用户不存在,请重新登录!");
		} else {
			return ssoToken;
		}
	}

	/**
	 * @desc 转换为 bootstrap-table 需要的分页格式 JSON
	 * @param page 分页对象
	 * @return String
	 */
	protected String jsonPage(PageInfo<?> page) {
		JSONObject object = new JSONObject();
		object.put("total", page.getTotal());
		object.put("rows", page.getList());
		return toJson(object);
	}

//	/**
//	 * @desc 忽略错误属性的JSON串
//	 * @param page 分页对象
//	 * @return 忽略错误的属性的JSON串
//	 */
//	protected String jsonPageIgnore(PageInfo<?> page) {
//		JSONObject object = new JSONObject();
//		object.put("total", page.getTotal());
//		object.put("rows", page.getList());
//		return toJsonIgnoreErrGetter(object);
//	}
}